package com.offcn.user.controller;

import com.offcn.dycommon.response.AppResponse;
import com.offcn.user.component.SmsTemplate;
import com.offcn.user.po.TMember;
import com.offcn.user.service.UserService;
import com.offcn.user.vo.req.UserRegistVo;
import com.offcn.user.vo.resp.UserRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
@Api(tags = "用户登录/注册模块（包括忘记密码等）")
public class UserLoginController {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/sendCode")
    @ApiOperation("获取注册的验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNo", value = "手机号", required = true)
    })
    public AppResponse<Object> sendCode(String phoneNo){
        //1、准备短信验证码，随机验证码 1233-3333-2222-3331
        String code = UUID.randomUUID().toString().substring(0, 4);
        System.out.println("生成的验证码:"+code);
        //2、把验证码存放到redis，为了后续校验验证码
        //验证码需要设置有效时间 5分钟
        redisTemplate.opsForValue().set(phoneNo,code,5, TimeUnit.MINUTES);

        //3、准备要发送短信数据，发送验证码到指定手机号码
        Map<String,String> querys=new HashMap<>();
        //设置要接收的手机号码
        querys.put("mobile",phoneNo);
        //设置验证码
        querys.put("param","code:"+code);
        //设置模板编号
        querys.put("tpl_id","TP1711063");

        String smsResponse = smsTemplate.smsSend(querys);
        //根据响应消息判断短信发送状态
        if(smsResponse.equals("")||smsResponse.equals("fail")){
            return AppResponse.fail("短信发送失败");
        }
        return AppResponse.ok(smsResponse);
    }

    //用户注册方法
    @ApiOperation("用户注册方法")
    @PostMapping("/regist")
    public AppResponse<Object> regist(UserRegistVo registVo){
        //1、校验短信验证码
        String mobile = registVo.getLoginacct();
        //根据手机号码，从redis读取对应验证码
        String smscodeRedis = redisTemplate.opsForValue().get(mobile);
        //判断从redis读取到验证码不为空
        if(!StringUtils.isEmpty(smscodeRedis)){

            //比对从redis读取到验证码，和前端用户输入短信验证码是否一致
            boolean b = smscodeRedis.equals(registVo.getCode());
            if(b){
                //短信验证码验证通过
                TMember member = new TMember();
                //借助于spring bean复制操作类，把VO的值复制到member对象
                BeanUtils.copyProperties(registVo,member);
                member.setUsername(registVo.getLoginacct());
                //调用service保存用户数据到数据库
                try {
                    userService.registerUser(member);
                    //成功注册
                    return AppResponse.ok("用户注册成功...");
                } catch (Exception e) {
                    e.printStackTrace();
                     log.error("用户注册失败:{}",member.getLoginacct());
                    return AppResponse.fail(e.getMessage());
                }

            }else {

                return AppResponse.fail("验证码验证失败");
            }
        }else {

            return AppResponse.fail("验证码已经过期");
        }
    }

    //用户登录方法
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })//@ApiImplicitParams：描述所有参数；@ApiImplicitParam描述某个参数
    @PostMapping("/login")
    public AppResponse<UserRespVo> login(String username,String password){
        //1、调用用户服务
        TMember member = userService.login(username, password);
        if(member==null){
            AppResponse<UserRespVo> appResponse = AppResponse.fail(null);
            //设置响应消息
            appResponse.setMsg("用户登录失败");

            return appResponse;

        }

        //2、当用户登录成功，生成令牌
        //1Q2W-WSS2-EEE3-33EE
        String token = UUID.randomUUID().toString().replace("-", "");
        //创建响应对象
        UserRespVo respVo = new UserRespVo();
        //设置其他属性
        BeanUtils.copyProperties(member,respVo);
        respVo.setAccessToken(token);

        //存储token到redis
        redisTemplate.opsForValue().set(token,member.getId()+"");

        return AppResponse.ok(respVo);

    }
}
